package com.etone.smartAudit.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.etone.smartAudit.domain.*;
import com.etone.smartAudit.dto.certificate.AddCertificateDTO;
import com.etone.smartAudit.dto.certificate.ApprovalFileDTO;
import com.etone.smartAudit.dto.certificate.CertificateHandDTO;
import com.etone.smartAudit.dto.egcc.MsgDTO;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.AdminMapper;
import com.etone.smartAudit.mapper.CertificateFileMapper;
import com.etone.smartAudit.security.SecurityUtils;
import com.sun.org.apache.bcel.internal.generic.INEG;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;

import static com.etone.smartAudit.domain.CertificatePerson.*;

/***
 * 存证单执行审批
 */
@Slf4j
@Service
public class CertificateFileApproval {


    @Autowired
    private CertificateUploadFileService certificateUploadFileService;

    @Autowired
    private CertificatePersonService personService;


    @Autowired
    private CertificateFileService fileService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CertificatePersonInfoService infoService;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private EGCCMService egccmService;

    @Autowired
    private CertificateFileMapper fileMapper;

    /***
     * 审批确认单
     * @param dto
     * @return
     */
    private CertificatePerson approValSureFile(CertificateHandDTO dto, ApprovalFileDTO approval) {
//        确认单： 1-【意见反馈】、2-【转派】、3-【退回】,领导【退回给部门经办人】 4-【情况属实，同意】 5-【情况不属实，请审计组核实】"
        //校验执行权限
        CertificatePerson person = approval.getCertificatePerson();
        CertificateFile file = approval.getCertificateFile();
        Integer status = dto.getState() == null ? 0 : dto.getState();
        if (status != 1) {
            file.setHandStatus(status);
            if (person.getId() != null && person.getId().equals(file.getHandPersonId())) {
                person.setState(status);
                person.setContent(dto.getContent());
            }
        }
//        person.setType(dto.getHandType());
        CertificatePerson forwadPerson = null;
        //获取执行人员类型
        Integer personType = person.getType() == null ? 0 : person.getType();
        switch (status) {
//            【意见反馈】
            case 1:
                //增加一个反馈对象，发送一条反馈信息
                dto.setCerType(1);
                handFeedBack(dto, person);
                break;
//                【转派】
            case 2:
                //获取扭转人员
                forwadPerson = forwardOption(file, person, dto);
                person.setForwordPersonId(forwadPerson.getId());
                file.setHandPersonId(forwadPerson.getId());
                break;
//               普通执行人 【退回】   仅可退回上一步执行人，不可退回给发起人，如上一步是发起人，则隐藏退回按钮  领导退回给部门经办人
            case 3:

                //获取上一步执行人
                Integer lastPersonid = person.getLastPersonId();
                if (1 == personType) {
                    //领导退回 领导退回给部门经办人  就是第一步执行人
                    //获取第一个执行人
                    CertificatePerson firstPerson = personService.getFirstHandPerson(file.getId());
                    if (firstPerson == null) {
                        throw new CustomParameterizedException("获取不到经办人");
                    }
                    forwadPerson = returnSureFile(file, firstPerson);
                } else {
                    //普通人退回
                    if (person.getIsFirst()) {
                        throw new CustomParameterizedException("该单已经在第一位执行人");
                    }
                    //获取上一步执行人 判断是不是发起人
                    CertificatePerson lastPerson = personService.getById(person.getLastPersonId());
                    forwadPerson = returnSureFile(file, lastPerson);
                }
                person.setForwordPersonId(forwadPerson.getId());
                break;
//                【情况属实，同意】
            case 4:
                // 【情况不属实，请审计组核实】
            case 5:
                // 领导执行，结束该单
                if (personType == 1) {
                    file.setState(1);
                } else {
                    //转派给领导
                    //获取扭转人员
                    forwadPerson = forwardOption(file, person, dto);
                    person.setForwordPersonId(forwadPerson.getId());
                    forwadPerson.setType(1);
                    file.setHandPersonId(forwadPerson.getId());
                }
                break;
            default:
                throw new CustomParameterizedException("请执行正确的审批");
        }
        file.setLastDate(LocalDateTime.now());
        file.setLastHandAdminId(person.getId());
        fileService.updateById(file);

        if (forwadPerson != null) {
            person.setForwordPerson(forwadPerson);
            personService.updateById(forwadPerson);
        }
        personService.updateById(person);
        if (status == 1) {
            //文件保存在forwd那
            CertificatePerson msgPerson = person.getMsgPerson();
            if (msgPerson != null) {
                msgPerson = handApprovalFileInfo(msgPerson, dto);
                personService.updateById(msgPerson);
                person.setDetails(msgPerson.getDetails());
            }
        } else {
            person = handApprovalFileInfo(person, dto);
        }
        //修改确认单各版本状态
        updateCerfileState(file);
        return person;

    }

    /***
     * 退回确认单
     */
    private CertificatePerson returnSureFile(CertificateFile file, CertificatePerson person) {
        CertificateHandDTO forwardDto = new CertificateHandDTO();
        forwardDto.setForwordPersonId(person.getPersonInfoId());
        forwardDto.setLastPersonId(person.getLastPersonId());
        CertificatePerson forwadPerson = forwardOption(file, person, forwardDto);
        file.setHandPersonId(forwadPerson.getId());
        return forwadPerson;
    }

    /***
     * 审批需求单
     * @param dto
     * @return
     */
    private CertificatePerson approValNeedFile(CertificateHandDTO dto, ApprovalFileDTO approval) {

        CertificatePerson person = approval.getCertificatePerson();
        CertificateFile file = approval.getCertificateFile();

        person.setUpdateTime(LocalDateTime.now());
//        person.setState(dto.getState());
//        "执行人执行状态;需求单：1-已阅，2-同意，3-不同意 4-意见反馈，
        //获取执行状态
        Integer status = dto.getState() == null ? 0 : dto.getState();
        if (status != 4) {//意见反馈不需要设置状态与反应内容
            if (person.getId() != null && person.getId().equals(file.getHandPersonId())) {
                person.setState(status);
                person.setContent(dto.getContent());
            }
            file.setHandStatus(status);
        }
        CertificatePerson forwadPerson = null;
//        转派”、“处理”“退回
        switch (status) {
//            1-已阅 ,执行扭转  转派
            case 1:
                //获取扭转人员
                forwadPerson = forwardOption(file, person, dto);
                file.setHandPersonId(forwadPerson.getId());
                forwadPerson.setType(0);
                person.setForwordPersonId(forwadPerson.getId());
                break;
//                2-同意，完成本次需求单,不需要做其他处理   处理
            case 2:
                file.setState(1);
//                file.setState(2);
//                给执行人发送已处理完成邮件
//                fileService.sendMsg(person, 3);
                log.info("========同意本次操作，审批流程完成，结束该单========");
                break;
//                ，3-不同意  退回给上一步执行人  退回
            case 3:
                //获取上一步执行人 判断是不是发起人
                CertificatePerson lastPerson = personService.getById(person.getLastPersonId());
                if (person.getIsFirst()) {//无退回权限
                    throw new CustomParameterizedException("当前为第一位执行人，不能执行退回");
                    //说明当前执行人是第一位执行人，退回给发起人，执行的就是不同意
                    //置空处理人，只有发起人自己能修改
//                    file.setHandPersonId(null);
//                    file.setCheckStatus(1);
//                    file.setState(1);
                } else {
                    //判断是否是发起人
                    CertificateHandDTO lastDto = new CertificateHandDTO();
                    lastDto.setForwordPersonId(lastPerson.getPersonInfoId());
                    lastDto.setLastPersonId(lastPerson.getLastPersonId());
                    forwadPerson = forwardOption(file, lastPerson, lastDto);
                    forwadPerson.setType(0);
                    //记录他的上一步执行人
                    person.setForwordPersonId(forwadPerson.getId());
                    file.setHandPersonId(forwadPerson.getId());
                }
                break;
//            4-意见反馈， 只反馈意见，不做任何流程执行
            case 4:
                //增加一个反馈对象，发送一条反馈信息
                dto.setCerType(0);
                handFeedBack(dto, person);
                break;
            default:
                throw new CustomParameterizedException("请填写正确的审批状态");
        }
        file.setLastDate(LocalDateTime.now());
        file.setLastHandAdminId(person.getId());
        fileService.updateById(file);
        personService.updateById(person);
        if (status == 4) {
            //文件保存在forwd那
            CertificatePerson msgPerson = person.getMsgPerson();
            if (msgPerson != null) {
                msgPerson = handApprovalFileInfo(msgPerson, dto);
                personService.updateById(msgPerson);
                person.setDetails(msgPerson.getDetails());
            }
        } else {
            person = handApprovalFileInfo(person, dto);
        }
        if (forwadPerson != null) {
            personService.updateById(forwadPerson);
            person.setForwordPerson(forwadPerson);
        }
        return person;
    }

    /**
     * 执行意见反馈
     */
    private void handFeedBack(CertificateHandDTO dto, CertificatePerson person) {
        AddCertificateDTO addCertificateDTO = new AddCertificateDTO();
        addCertificateDTO.setHandPersonInfoId(dto.getFeedBackInfoId());
        CertificatePerson msgPerson = fileService.getHandPerson(addCertificateDTO);
        msgPerson.setType(4);//代表是反馈
        msgPerson.setOptionPersonId(person.getId());
        msgPerson.setOptionPersonName(person.getName());
        msgPerson.setCerFileid(person.getCerFileid());
        msgPerson.setContent(dto.getContent());
        personService.save(msgPerson);
        person.setForwordPersonId(msgPerson.getId());
//        person.setContent(null);
        person.setMsgPerson(msgPerson);
        //发送消息

//        egccmService.sendEmsg(person.getPhone(),person.getCode(),person.getUrl());
        fileService.sendMsg(msgPerson, 2);
    }

    /***
     * 执行扭转操作，扭转，或者需求单的不同意也是扭转回上一步执行人
     */
    private CertificatePerson forwardOption(CertificateFile file, CertificatePerson person, CertificateHandDTO dto) {
        //获取扭转人员
        CertificatePerson forwardPerson = getNewForwardPerson(file, person, dto);
        //获取下一步执行人
        if (forwardPerson == null) {
            throw new CustomParameterizedException("扭转人员不存在");
        } else {
            person.setForwordPersonId(forwardPerson.getId());
            //修改为下一个执行人
            file.setHandPersonId(forwardPerson.getId());
        }
        return forwardPerson;
    }

    /***
     * 验证用户是否有执行权限
     * @param dto
     * @return
     */
    private ApprovalFileDTO verifyPersonHasPermission(CertificateHandDTO dto) {
        ApprovalFileDTO approvalFileDTO = new ApprovalFileDTO();
        // 获取当前登录用户
        String loginAdminName = SecurityUtils.getCurrentUserLogin();
        Admin admin = adminMapper.findByAccount(loginAdminName);
        if (admin == null) {
            admin = new Admin();
        }
        //是否是管理员
        boolean isAdmin = admin != null && admin.isAdmin();

        if (!isAdmin && dto.getPersonId() == null) {
            throw new CustomParameterizedException("执行人信息不能为空");
        }
        CertificatePerson person = personService.getById(dto.getPersonId());
        if (!isAdmin && person == null) {
            throw new CustomParameterizedException("执行人不存在");
        }
        //获取存证单
        CertificateFile file = fileService.getById(person.getCerFileid());

        if (file == null) {
            throw new CustomParameterizedException("存证单已不存在!");
        }

        if (CertificateFile.STATE_COMPLETE.equals(file.getState())) {
            throw new CustomParameterizedException("该单已完结,不能再执行!");
        }
        LocalDateTime endTime = file.getEndTime();
//        .toInstant(ZoneOffset.of("+8")).toEpochMilli();
        if (System.currentTimeMillis() > endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) {
            log.error("已经截止改单");

//            throw new CustomParameterizedException("该单已经截止!");
        }

        if (admin.getId() != null && admin.getId().equals(dto.getPersonId())) {
            //如果是管理员执行，则赋值到第一位执行人
            person = personService.getById(file.getHandPersonId());
            if (person == null) {
                throw new CustomParameterizedException("执行人信息不存在");
            }
        }

        //如果是意见反馈不需要执行权限验证
        Integer state = dto.getState();
        Integer type = file.getType();
        boolean isFeekBak = false;
        if (type != null && type == 1 && state != null && state == 4) {
            isFeekBak = true;
        }
        if (type != null && type == 2 && state != null && state == 1) {
            isFeekBak = true;
        }

        //验证token
        String verfiToken = getHandToken(person.getCode(), person.getUrl());

        //校验执行人是否是在执行其
        if (!isFeekBak) {
            if (!isAdmin) {
                personService.hasHandPermission(person);
//                if (StrUtil.isEmpty(verfiToken) || !verfiToken.equals(dto.getToken())) {
//                    log.error(JSON.toJSONString(dto));
//                    throw new CustomParameterizedException("您没有操作权限");
//                }
            }
        }
        approvalFileDTO.setCertificatePerson(person);
        approvalFileDTO.setCertificateFile(file);
        return approvalFileDTO;
    }

    /***
     * 执行审批流程
     * @param dto
     * @return
     */
    public CertificatePerson ApprovalCertificate(CertificateHandDTO dto) {
        //校验执行权限
        ApprovalFileDTO approval = verifyPersonHasPermission(dto);
        CertificateFile file = approval.getCertificateFile();
        CertificatePerson person = approval.getCertificatePerson();

        //执行抄送发送
        file.setCopySendPersonInfoIds(dto.getCopySendPersonInfoIds());
        fileService.copySendMsg(file, person);

        if (CertificateFile.NEED_TYPE.equals(file.getType())) {
            return approValNeedFile(dto, approval);
        } else {
            return approValSureFile(dto, approval);
        }
    }

    /***
     * 执行审批
     * @param dto
     * @return
     */
    @Deprecated
    public CertificatePerson ApprovalCertificateold(CertificateHandDTO dto) {
        ApprovalFileDTO approval = verifyPersonHasPermission(dto);
        CertificatePerson person = approval.getCertificatePerson();
        CertificateFile file = approval.getCertificateFile();

        person.setUpdateTime(LocalDateTime.now());
        person.setContent(dto.getContent());
        person.setState(dto.getState());
        //获取扭转人员
        CertificatePerson forwardPerson = getForwardPerson(file, person, dto);
        if (forwardPerson != null) {
            person.setForwordPersonId(forwardPerson.getId());
            //修改为下一个执行人
            file.setHandPersonId(forwardPerson.getId());
        }

        //保存文件
        certificateUploadFileService.saveFile(dto.getFiles(), person.getId(), CertificateUploadFile.HAND_PERSON_FILE);
        personService.updateById(person);

        //更新file状态
        file.setLastDate(LocalDateTime.now());
        Integer personHandStatus = person.getHandStatus() == null ? 0 : person.getHandStatus();
        file.setLastHandAdminId(person.getId());
        if (personHandStatus != 1) {
            //领导退回给执行人的状态下不更改文件状态
            file.setHandStatus(dto.getState());
            setFileState(file, person, dto);
        }
        //修改确认单各版本状态
        updateCerfileState(file);
        //获取文件信息
        LambdaQueryWrapper<CertificateUploadFile> query = new LambdaQueryWrapper<>();
        query.eq(CertificateUploadFile::getType, CertificateUploadFile.HAND_PERSON_FILE);
        query.in(CertificateUploadFile::getRelativeId, person.getId());
        List<CertificateUploadFile> files = certificateUploadFileService.list(query);
        person.setFiles(files);
        if (forwardPerson != null) {
            person.setForwordPerson(forwardPerson);
        }
        person.setDetails(fileService.getPersonInfo(person));
        //删除文件
        fileUploadService.deleteFileByFileVO(dto.getFiles(), false, true);
        return person;
    }

    /***
     * 处理审批文件信息
     */
    private CertificatePerson handApprovalFileInfo(CertificatePerson person, CertificateHandDTO dto) {
        //保存文件
        certificateUploadFileService.saveFile(dto.getFiles(), person.getId(), CertificateUploadFile.HAND_PERSON_FILE);
        //获取文件信息
        LambdaQueryWrapper<CertificateUploadFile> query = new LambdaQueryWrapper<>();
        query.eq(CertificateUploadFile::getType, CertificateUploadFile.HAND_PERSON_FILE);
        query.in(CertificateUploadFile::getRelativeId, person.getId());
        List<CertificateUploadFile> files = certificateUploadFileService.list(query);
        person.setFiles(files);
        person.setDetails(fileService.getPersonInfo(person));
        //删除文件
        fileUploadService.deleteFileByFileVO(dto.getFiles(), false, true);
        return person;
    }

    /***
     * 获取新流程的扭转人员
     * @param file
     * @param person
     * @param dto
     * @return
     */
    private CertificatePerson getNewForwardPerson(CertificateFile file, CertificatePerson person, CertificateHandDTO dto) {
        //获取扭转人员信息
        Integer forwardPersonInfoId = dto.getForwordPersonId();
        //获取扭转人信息
        CertificatePersonInfo personInfo = infoService.getById(forwardPersonInfoId);
        if (personInfo == null) {
            throw new CustomParameterizedException("不具备扭转人信息!");
        }
        //添加扭转人
        CertificatePerson forwordPerson = new CertificatePerson();
        forwordPerson.setName(personInfo.getName());
        forwordPerson.setPhone(personInfo.getPhone());
        forwordPerson.setEmail(personInfo.getEmail());
//        if (!isNeedFile && person.getType() == CertificatePerson.NORMAL_PERSON) {
//            //如果是确认单且是普通人执行的扭转，则扭转的人员是领导类型
//            forwordPerson.setType(CertificatePerson.LEADER_PERSON);
//        } else {
//            forwordPerson.setType(CertificatePerson.NORMAL_PERSON);
//        }
        //创建连接地址  //创建验证码
        forwordPerson.setUrl(IdUtil.fastSimpleUUID());
        forwordPerson.setCode(RandomUtil.randomStringUpper(CertificateFileService.CODE_LENGTH));
        forwordPerson.setState(CertificatePerson.NO_HAND);
        forwordPerson.setCerFileid(file.getId());
        forwordPerson.setUpdateTime(LocalDateTime.now());
        forwordPerson.setCreateTime(LocalDateTime.now());
        forwordPerson.setPersonInfoId(personInfo.getId());
        //判断扭转回去的人是否是第一位
        LambdaQueryWrapper<CertificatePerson> query = new LambdaQueryWrapper<>();
        query.eq(CertificatePerson::getCerFileid, person.getCerFileid())
                .eq(CertificatePerson::getPersonInfoId, personInfo.getId());
        List<CertificatePerson> list = personService.list(query);
        if (CollectionUtil.isNotEmpty(list)) {
            forwordPerson.setIsFirst(list.get(0).getIsFirst());
        }

        Integer state = file.getHandStatus();
        Integer type = file.getType();
        boolean isRebak = false;
        if (type != null && type == 1 && state != null && state == 3) {
            isRebak = true;
        }
        if (type != null && type == 2 && state != null && state == 3) {
            isRebak = true;
        }
        if (isRebak) {
            //记录上一步扭转人信息
//            Integer lastPersonId = person.getLastPersonId();
//            if (lastPersonId != null) {
//                CertificatePerson temp = personService.getById(lastPersonId);
            forwordPerson.setLastPersonId(dto.getLastPersonId());
//            }
        } else {
            //记录上一个扭转人员
            forwordPerson.setLastPersonId(person.getId());
        }
//        forwordPerson.setIsFirst(person.getIsFirst());
        forwordPerson.setVersion((person.getVersion() == null ? 0 : person.getVersion()) + 1);
        personService.save(forwordPerson);
        return forwordPerson;
    }

    /***
     * 获取扭转人员
     * @param person
     * @param dto
     * @return
     */
    @Deprecated
    private CertificatePerson getForwardPerson(CertificateFile file, CertificatePerson person, CertificateHandDTO dto) {
        Integer type = file.getType();
        //是否是需求单
        Integer forwardPersonInfoId = null;
        //是否是扭转
        boolean isForward = false;

        //是否是需求单不同意
        boolean isNeedNotAgree = false;

        //执行人执行状态，0-正常执行，1-领导不同意返回跟上一步执行人的状态
        Integer handStatus = 0;

        boolean isNeedFile = CertificateFile.NEED_TYPE.equals(type);
        if (isNeedFile) {
            if (dto.getState() == CertificatePerson.YET_READ) {
                //扭转需要指定扭转人
                forwardPersonInfoId = dto.getForwordPersonId();
                if (forwardPersonInfoId == null) {
                    throw new CustomParameterizedException("请指定扭转人");
                }
                isForward = true;
            } else if (dto.getState() == CertificatePerson.NO_AGREE) {
                //需求单不同意，扭转回上一步执行人
                //获取上一个执行人
                CertificatePerson lastForwardPerson = personService.getById(person.getLastPersonId());
                isNeedNotAgree = true;
                if (lastForwardPerson != null) {
                    forwardPersonInfoId = lastForwardPerson.getPersonInfoId();
                }
            }
        } else {
            //确认单
            //普通执行人同意 则扭转至领导
            if (person.getType() == NORMAL_PERSON) {
                Integer personHandStatus = person.getHandStatus() == null ? 0 : person.getHandStatus();
                if (dto.getState() == CertificatePerson.YES_AGREE) {
                    //如果当前执行人不是领导的情况
                    if (file.getLeaderAdminId() != null && !file.getLeaderAdminId().equals(person.getPersonInfoId())) {
                        if (personHandStatus == 0) {
                            forwardPersonInfoId = file.getLeaderAdminId();
                        } else {
                            //此处是领导审批回来的执行，同意则结束

                        }
                    }
                } else {
                    //普通执行人不同意
                    if (file.getLeaderAdminId() != null && !file.getLeaderAdminId().equals(person.getPersonInfoId())) {
                        if (personHandStatus == 1) {
                            //此处是领导审批回来的执行，不同意，则返回给领导
                            forwardPersonInfoId = file.getLeaderAdminId();
                        }
                    }
                }
            } else if (person.getType() == LEADER_PERSON && dto.getState() == CertificatePerson.NO_AGREE) {
                //领导不同意则扭转给上一个执行人
                CertificatePerson lastForwardPerson = personService.getById(person.getLastPersonId());
                forwardPersonInfoId = lastForwardPerson.getPersonInfoId();
                handStatus = 1;
            }
        }
        if (forwardPersonInfoId != null) {
            //获取扭转人信息
            CertificatePersonInfo personInfo = infoService.getById(forwardPersonInfoId);
            //添加扭转人
            CertificatePerson forwordPerson = new CertificatePerson();
            forwordPerson.setName(personInfo.getName());
            forwordPerson.setPhone(personInfo.getPhone());
            forwordPerson.setEmail(personInfo.getEmail());
            if (!isNeedFile && person.getType() == CertificatePerson.NORMAL_PERSON) {
                //如果是确认单且是普通人执行的扭转，则扭转的人员是领导类型
                forwordPerson.setType(CertificatePerson.LEADER_PERSON);
            } else {
                forwordPerson.setType(CertificatePerson.NORMAL_PERSON);
            }
            //创建连接地址  //创建验证码
            forwordPerson.setUrl(IdUtil.fastSimpleUUID());
            forwordPerson.setCode(RandomUtil.randomStringUpper(CertificateFileService.CODE_LENGTH));
            forwordPerson.setState(CertificatePerson.NO_HAND);
            forwordPerson.setCerFileid(file.getId());
            forwordPerson.setUpdateTime(LocalDateTime.now());
            forwordPerson.setCreateTime(LocalDateTime.now());
            forwordPerson.setPersonInfoId(personInfo.getId());

            if (isForward) {
                //如果是扭转的记录当前扭转人信息
                forwordPerson.setLastPersonId(person.getId());
            } else if (isNeedNotAgree) {
                //记录上一步扭转人信息
                Integer lastPersonId = person.getLastPersonId();
                if (lastPersonId != null) {
                    CertificatePerson temp = personService.getById(lastPersonId);
                    forwordPerson.setLastPersonId(temp.getLastPersonId());
                }
            } else {
                //如果是确认单也记录上一个执行人
                if (!isNeedFile && handStatus != 1) {
                    forwordPerson.setLastPersonId(person.getId());
                }
            }
            forwordPerson.setHandStatus(handStatus);
            personService.save(forwordPerson);
            return forwordPerson;
        }
        return null;
    }

    /***
     * 处理单完成
     * @param file
     */
    private void updateCerfileState(CertificateFile file) {
        Integer type = file.getType();
        if (type == CertificateFile.CONFIRM_TYPE) {
            //如果是确认单，则各个版本的状态都的设为一样
            LambdaUpdateWrapper<CertificateFile> query = new LambdaUpdateWrapper<>();
            query.set(CertificateFile::getState, file.getState());
            query.eq(CertificateFile::getFileGroupId, file.getFileGroupId());
            fileService.update(query);
        }
        fileService.updateById(file);
    }

    /***
     * 设置文件状态
     * @param file
     * @param person
     * @param dto
     * @return
     */
    private void setFileState(CertificateFile file, CertificatePerson person, CertificateHandDTO dto) {
        Integer fileType = file.getType();
        //需求单同意后则完结
        if (fileType.equals(CertificateFile.NEED_TYPE) && dto.getState().equals(YES_AGREE)) {
            //设置状态为已完成
            file.setState(CertificateFile.STATE_COMPLETE);
        } else if (fileType.equals(CertificateFile.CONFIRM_TYPE) && (person.getType().equals(LEADER_PERSON) || person.getPersonInfoId().equals(file.getLeaderAdminId()))) {
            //领导执行确认单已完结
            file.setState(CertificateFile.STATE_COMPLETE);
        } else if (fileType.equals(CertificateFile.CONFIRM_TYPE) && person.getType().equals(NORMAL_PERSON) && dto.getState().equals(NO_AGREE)) {
            //普通执行者不同意为已完结
            file.setState(CertificateFile.STATE_COMPLETE);
        }
    }

    /**
     * 获取token
     *
     * @param code
     * @param loginKey
     * @return
     */
    public String getHandToken(String code, String loginKey) {
        return fileService.getHandToken(code, loginKey);
//        MD5 md5 = new MD5(code.getBytes(StandardCharsets.UTF_8));
//        String token = md5.digestHex(code);
//        return token;
    }
}
